package com.yixun.lbx.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ServerEndpoint("/websocket")
@Component
public class WebSocket {
    //记录当前在线连接数
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    // 存放所有在线的客户端
    private static  Map<String, Session> clients = new ConcurrentHashMap<>();


    // 连接建立成功调用的方法
    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        clients.put(session.getId(), session);
    }

    //连接关闭调用的方法
    
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(session.getId());
    }

    
    /* 收到客户端消息后调用的方法
     @param message 客户端发送过来的消息*/
     
    @OnMessage
    public void onMessage(String message,@Nullable Session session) {
        this.sendMessage(message, session);
    }
    @OnError
    public void onError( Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

   /* *
     * 群发消息
     * @param message 消息内容*/
     
    private void sendMessage(String message,@Nullable Session fromSession) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            toSession.getAsyncRemote().sendText(message);
        }
    }
}
